﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using yncTech.BusinessObjects;
using System.Data;
using System.Collections;

using EntitySpaces.Interfaces;


public partial class Admin_FinMov_FinMov001g : AdminBasePage
{
    protected string show = "hide";
    decimal shipID = -1;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Request.QueryString[FinShippingMetadata.ColumnNames.ShipID] != null)
        {
            shipID = decimal.Parse(Request.QueryString[FinShippingMetadata.ColumnNames.ShipID]);
        }
        if (!IsPostBack)
        {
            //drpLocation.Items.Insert(1, new ListItem("未分配存储", "未分配存储"));

            txtStartDate.Value = DateTime.Now.AddMonths(-1).Date.ToString(ConstantValue.DateFormat);
            txtEndate.Value = DateTime.Now.ToString(ConstantValue.DateFormat);
            drpCreator.SelectedValue = LoginUserInfo.CurrentUser.UserName;

            if (Session["sd"] != null)
            {
                txtStartDate.Value = Session["sd"].ToString();
            }
            if (Session["ed"] != null)
            {
                txtEndate.Value = Session["ed"].ToString();
            }
            if (Session["drpYearStart"] != null)
            {
                drpYearStart.SelectedValue = Session["drpYearStart"].ToString();
            }
            if (Session["drpMonthStart"] != null)
            {
                drpMonthStart.SelectedValue = Session["drpMonthStart"].ToString();
            }
            if (Session["drpYearEnd"] != null)
            {
                drpYearEnd.SelectedValue = Session["drpYearEnd"].ToString();
            }
            if (Session["drpMonthEnd"] != null)
            {
                drpMonthEnd.SelectedValue = Session["drpMonthEnd"].ToString();
            }
            if (Session["txtBoxNo"] != null)
            {
                txtBoxNo.Text = Session["txtBoxNo"].ToString();
            }
            if (Session["drpDocType"] != null)
            {
                drpDocType.SelectedValue = Session["drpDocType"].ToString();
            }
            if (Session["drpCompany"] != null)
            {
                drpCompany.SelectedValue = Session["drpCompany"].ToString();
            }
            if (Session["drpFunctionDept"] != null)
            {
                drpFunctionDept.SelectedValue = Session["drpFunctionDept"].ToString();
            }
            if (Session["drpLocation"] != null)
            {
                drpLocation.SelectedValue = Session["drpLocation"].ToString();
            }
            if (Session["drpCabin"] != null)
            {
                drpCabin.SelectedValue = Session["drpCabin"].ToString();
            }
            if (Session["drpNumber"] != null)
            {
                drpNumber.SelectedValue = Session["drpNumber"].ToString();
            }
            if (Session["drpCreator"] != null)
            {
                drpCreator.SelectedValue = Session["drpCreator"].ToString();
            }
        }

    }

    protected void btnSearch_Click(object sender, EventArgs e)
    {
        GridDataBind(1);
        //Session["sd"] = txtStartDate.Value;
        //Session["ed"] = txtEndate.Value;
        //Session["drpYearStart"] = drpYearStart.SelectedValue;
        //Session["drpMonthStart"] = drpMonthStart.SelectedValue;
        //Session["drpYearEnd"] = drpYearEnd.SelectedValue;
        //Session["drpMonthEnd"] = drpMonthEnd.SelectedValue;
        //Session["txtBoxNo"] = txtBoxNo.Text.Trim();
        //Session["drpDocType"] = drpDocType.SelectedValue;
        //Session["drpCompany"] = drpCompany.SelectedValue;
        //Session["drpFunctionDept"] = drpFunctionDept.SelectedValue;
        //Session["drpLocation"] = drpLocation.SelectedValue;
        //Session["drpCabin"] = drpCabin.SelectedValue;
        //Session["drpNumber"] = drpNumber.SelectedValue;
        //Session["drpCreator"] = drpCreator.SelectedValue;
        //Response.Redirect("FinMov001g.aspx?" + FinShippingMetadata.ColumnNames.ShipID + "=" + shipID.ToString());
    }


    protected void PageChanged(object sender, DataGridPageChangedEventArgs e)
    {
        if (IsPostBack)
        {
            return;
        }
        GridDataBind(e.NewPageIndex);
    }
    void GridDataBind(int page)
    {
        FinBoxQuery q1 = new FinBoxQuery("q1");
        BFThirdUnitQuery q2 = new BFThirdUnitQuery("q2");
        TSCodeTableQuery q3 = new TSCodeTableQuery("q3");
        TSCodeTableQuery q4 = new TSCodeTableQuery("q4");
        TSCodeTableQuery q5 = new TSCodeTableQuery("q5");
        //BFCompanyDicQuery q6 = new BFCompanyDicQuery("q6");

        ArrayList args = new ArrayList();
        args.Add(q1.CreatedDttm >= txtStartDate.Value);
        args.Add(q1.CreatedDttm <= DateTime.Parse(txtEndate.Value).AddDays(1));
        args.Add(q1.StorageStatus == "S2");//只查询在库的凭证盒
        args.Add(q1.BoxNo.IsNotNull());
        args.Add(q1.BoxNo != "");



        if (!string.IsNullOrEmpty(drpYearStart.SelectedValue + drpMonthStart.SelectedValue))
        {
            args.Add(q1.BoxYear >= drpYearStart.SelectedValue);
            args.Add(q1.BoxMonth >= drpMonthStart.SelectedValue);
        }

        if (!string.IsNullOrEmpty(drpYearEnd.SelectedValue + drpMonthEnd.SelectedValue))
        {
            args.Add(q1.BoxYearEnd <= drpYearEnd.SelectedValue);
            args.Add(q1.BoxMonthEnd <= drpMonthEnd.SelectedValue);
        }
        if (!string.IsNullOrEmpty(txtBoxNo.Text.Trim()))
        {
            args.Add(q1.BoxNo.Like("%" + txtBoxNo.Text.Trim() + "%"));
        }
        if (!string.IsNullOrEmpty(drpDocType.SelectedValue) && drpDocType.SelectedValue != "N/A")
        {
            args.Add(q1.DocumentType == drpDocType.SelectedValue);
        }
        if (!string.IsNullOrEmpty(drpCompany.SelectedValue) && drpCompany.SelectedValue != "N/A")
        {
            args.Add(q1.CompanyName == drpCompany.SelectedValue.Split(',')[0]);
            args.Add(q1.CompanyCode == drpCompany.SelectedValue.Split(',')[1]);
        }
        if (!string.IsNullOrEmpty(drpFunctionDept.SelectedValue))
        {
            args.Add(q1.FunctionDept == drpFunctionDept.SelectedValue);
        }
        if (!string.IsNullOrEmpty(drpLocation.SelectedValue))
        {
            args.Add(q1.BoxLocation == drpLocation.SelectedValue);
        }
        if (!string.IsNullOrEmpty(drpCabin.SelectedValue))
        {
            args.Add(q1.ThirdUnitCabinId == drpCabin.SelectedValue);
        }
        if (!string.IsNullOrEmpty(drpNumber.SelectedValue))
        {
            args.Add(q1.ThirdUnitNumberId == drpNumber.SelectedValue);
        }
        if (!string.IsNullOrEmpty(drpCreator.SelectedValue))
        {
            args.Add(q1.CreatedBy == drpCreator.SelectedValue);
        }

        q1.LeftJoin(q2).On(q1.BoxLocation == q2.ThirdUnitID);
        q1.InnerJoin(q3).On(q1.DocumentType == q3.Code);
        q1.InnerJoin(q4).On(q1.FunctionDept == q4.Code);
        q1.InnerJoin(q5).On(q1.StorageStatus == q5.Code);
        //q1.InnerJoin(q6).On(q1.CompanyCode == q6.CompanyNo);


        q1.Select(q1.CompanyCode, q1.BoxID, (q2.Name + q2.CartName).As("LocationName"), q3.CodeDesc.As("DocumentTypeName"), q4.CodeDesc.As("FunctionDeptName")
            , q5.CodeDesc.As("StorageStatusName"), q1.CreatedBy, q1.UpdatedBy, q1.CreatedDttm, q1.UpdatedDttm, q1.CompanyName, q1.BoxYear, q1.BoxMonth, q1.CompanyCode, q1.BoxNo, q1.BoxMonthEnd)
            .Where(args.ToArray())
            .OrderBy(q1.CreatedDttm.Descending);

        q1.es.Top = 100;

        pageGrid.DataSource = q1.LoadDataTable();
        pageGrid.CurrentPage = page;
        pageGrid.DataBind();
    }



    protected override void OnUnload(EventArgs e)
    {
        base.OnUnload(e);
        Session.Remove("sd");
        Session.Remove("ed");
        Session.Remove("drpYearStart");
        Session.Remove("drpMonthStart");
        Session.Remove("drpYearEnd");
        Session.Remove("drpMonthEnd");
        Session.Remove("txtBoxNo");
        Session.Remove("drpDocType");
        Session.Remove("drpCompany");
        Session.Remove("drpFunctionDept");
        Session.Remove("drpLocation");
        Session.Remove("drpCabin");
        Session.Remove("drpNumber");
        Session.Remove("drpCreator");

    }


    protected int GetDocumentCount(object boxId)
    {
        int result = 0;
        if (boxId != null)
        {
            FinBoxReceiptsCollection finBoxReceiptsCollection = new FinBoxReceiptsCollection();
            finBoxReceiptsCollection.Query.Where(finBoxReceiptsCollection.Query.BoxID == boxId.ToString());
            finBoxReceiptsCollection.Query.Load();
            result = finBoxReceiptsCollection.Count;
        }
        return result;
    }


    protected void drpLocation_OnSelectedIndexChanged(object sender, EventArgs e)
    {
        if (!string.IsNullOrEmpty(drpLocation.SelectedValue))
        {
            BFThirdUnitCabinCollection bFThirdUnitCabinCollection = new BFThirdUnitCabinCollection();
            bFThirdUnitCabinCollection.Query.Where(bFThirdUnitCabinCollection.Query.ThirdUnitID == decimal.Parse(drpLocation.SelectedValue))
                .OrderBy(bFThirdUnitCabinCollection.Query.Name.Ascending);
            bFThirdUnitCabinCollection.Query.Load();
            drpCabin.DataSource = bFThirdUnitCabinCollection;
            drpCabin.DataTextField = BFThirdUnitCabinMetadata.ColumnNames.Name;
            drpCabin.DataValueField = BFThirdUnitCabinMetadata.ColumnNames.ThirdUnitCabinID;
            drpCabin.DataBind();

            drpCabin.Items.Insert(0, new ListItem("请选择凭证仓库号", ""));
            show = "show";
        }
    }

    protected void drpCabin_OnSelectedIndexChanged(object sender, EventArgs e)
    {
        if (!string.IsNullOrEmpty(drpCabin.SelectedValue))
        {
            BFThirdUnitNumberCollection bFThirdUnitNumberCollection = new BFThirdUnitNumberCollection();
            bFThirdUnitNumberCollection.Query.Where(bFThirdUnitNumberCollection.Query.ThirdUnitCabinID == Guid.Parse(drpCabin.SelectedValue))
                .OrderBy(bFThirdUnitNumberCollection.Query.Name.Ascending);
            bFThirdUnitNumberCollection.Query.Load();
            drpNumber.DataSource = bFThirdUnitNumberCollection;
            drpNumber.DataTextField = BFThirdUnitNumberMetadata.ColumnNames.Name;
            drpNumber.DataValueField = BFThirdUnitNumberMetadata.ColumnNames.ThirdUnitNumberID;
            drpNumber.DataBind();

            drpNumber.Items.Insert(0, new ListItem("请选择凭证柜号", ""));

            show = "show";
        }
    }

    protected void btnSave_Click(object sender, EventArgs e)
    {
        try
        {
            lbMessage.Text = "";
            FinShippingBoxes fsb = new yncTech.BusinessObjects.FinShippingBoxes();
            FinBox finBox = new yncTech.BusinessObjects.FinBox();
            using (esTransactionScope tr = new esTransactionScope())
            {
                foreach (RepeaterItem item in pageGrid.Items)
                {
                    CheckBox chkBox = (CheckBox)item.FindControl("chk_sel");
                    if (chkBox.Checked)
                    {
                        Label lbBox = (Label)item.FindControl("lbBoxID");
                        fsb.BoxID = decimal.Parse(lbBox.Text);
                        fsb.ShipID = shipID;
                        fsb.UpdatedBy = fsb.CreatedBy = LoginUserInfo.CurrentUser.LoginName;
                        fsb.UpdatedDttm = fsb.CreatedDttm = DateTime.Now;
                        fsb.Save();

                        //添加后将box的状态设置为:待转移
                        finBox.LoadByPrimaryKey(fsb.BoxID.Value);
                        finBox.StorageStatus = ConstantValue.StorageStatusCode.PendingTransfer;
                        finBox.UpdatedBy = LoginUserInfo.CurrentUser.LoginName;
                        finBox.UpdatedDttm = DateTime.Now;
                        finBox.Save();
                        //将盒中的凭证也设置为:待转移

                        FinBoxReceiptsCollection boxRecs = new yncTech.BusinessObjects.FinBoxReceiptsCollection();
                        boxRecs.Query.Where(boxRecs.Query.BoxID == fsb.BoxID.Value,boxRecs.Query.ReceiptID.IsNotNull());
                        boxRecs.Query.Load();

                        if (boxRecs.Count > 0)
                        {
                            FinReceiptCollection receipts = new yncTech.BusinessObjects.FinReceiptCollection();
                            receipts.Query.Where(receipts.Query.ReceiptID.In(boxRecs.Select(r => r.ReceiptID.Value).ToArray()));
                            receipts.Query.Load();
                            foreach (var rec in receipts)
                            {
                                rec.StorageStatus = ConstantValue.StorageStatusCode.PendingTransfer;
                                rec.UpdatedBy = LoginUserInfo.CurrentUser.LoginName;
                                rec.UpdatedDttm = DateTime.Now;
                            }
                            receipts.Save();
                        }


                    }
                }
                tr.Complete();
            }

            Response.Redirect("FinMov001.aspx");

        }
        catch (Exception ex)
        {
            lbMessage.Text = ex.Message;
        }
    }

    protected void btnRetrun_Click(object sender, EventArgs e)
    {
        Response.Redirect("FinMov001.aspx");
    }
}